<script setup lang="ts">
import { Dialog, Form, Field, CellGroup, showNotify, Picker, Popup } from "vant";
import type { FormInstance } from "vant";
import { reactive, ref, onMounted } from "vue";
import axios from "axios";
import { useConfigStore } from "@/stores/models/config";

const configStore = useConfigStore();

const dialogData = reactive({
    visible: false,
    loading: false
});

onMounted(() => {
    axios
        .get(`http://${configStore.device_ip}/wifi_list.json`)
        .then((res) => {
            options.value = res.data.map((item: string[]) => {
                return { text: item[0], value: item[0] };
            });
        })
        .catch(() => {
            showNotify("加载WIFI列表失败");
        });
});

const showPicker = ref(false);
const options = ref<{ text: string; value: string }[]>([]);
const handleConfirm = (e: any): void => {
    formData.name = e.selectedOptions[0]?.text;
    showPicker.value = false;
};
const handleShowPicker = (): void => {
    if (!dialogData.loading) {
        showPicker.value = true;
    }
};

const formData = reactive({
    name: "",
    pwd: ""
});
const formRef = ref<FormInstance | null>(null);
const handleSetWifi = async (action: string): Promise<boolean> => {
    if (action !== "confirm") return true;
    try {
        await formRef.value?.validate();
        dialogData.loading = true;
        const data = {
            name: formData.name,
            pwd: formData.pwd
        };
        await axios({
            url: `http://${configStore.device_ip}/set/wifi`,
            method: "post",
            data
        });
        configStore.$patch({ wifi: data });
        showNotify({ type: "success", message: "设置成功" });
        return true;
    } catch (error) {
        showNotify({ type: "danger", message: "设置失败" });
        return false;
    }
};

const handleShow = (): void => {
    dialogData.visible = true;
};

defineExpose({
    show: handleShow
});
</script>
<template>
    <Dialog
        v-model:show="dialogData.visible"
        title="连接WIFI"
        show-cancel-button
        :before-close="handleSetWifi"
        close-on-click-overlay
        :cancel-button-disabled="dialogData.loading"
    >
        <Form class="my-4" :disabled="dialogData.loading" ref="formRef">
            <CellGroup inset>
                <Field
                    required
                    v-model="formData.name"
                    is-link
                    readonly
                    name="picker"
                    label="WIFI名称"
                    label-align="top"
                    placeholder="点击选择WIFI"
                    @click="handleShowPicker"
                    :rules="[{ required: true, message: '请选择WIFI' }]"
                />
                <Field
                    label="WIFI密码"
                    label-align="top"
                    placeholder="请输入设备局域网IP地址"
                    v-model="formData.pwd"
                />
            </CellGroup>
        </Form>
    </Dialog>
    <Popup v-model:show="showPicker" position="bottom">
        <Picker :columns="options" @confirm="handleConfirm" @cancel="showPicker = false" />
    </Popup>
</template>
